import { Login, getInfo, getUserDetailById } from '../../api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const getDefaultState = () => {
  return {
    token: getToken() || '',
    name: '',
    avatar: '',
    userinfo: {}

  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  setToken: (state, token) => {
    state.token = token
    // localStorage.setItem('token', token)
    setToken(token)
  },
  setUserInfo(state, v) {
    state.userinfo = v
  },
  removeUserInfo(state, v) {
    state.userinfo = ''
  },
  logout(state) {
    state.userinfo = {}
    state.token = ''
    removeToken()
  }

}

const actions = {
  // user login
  login(store, v) {
    return new Promise((reserve, reject) => {
      Login(v).then(res => {
        // console.log(res)
        store.commit('setToken', res.data)
        reserve(res)
      })
    })
  },
  // 获取用户基本信息
  asyncUserInfo(store, v) {
    return new Promise((reserve, reject) => {
      getInfo().then(res => {
        console.log(res)
        getUserDetailById(res.data.userId).then(imgRes => {
          console.log(imgRes)
          store.commit('setUserInfo', { ...imgRes.data, ...res.data })
          reserve({ ...imgRes, ...res })
        })
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

